package com.buydeem.share.rabbit.dead;

import com.buydeem.share.rabbit.Utils;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 *
 * @author zengchao
 * @date 2021-05-11 12:05:05
 */
@Slf4j
public class ConsumerApp {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = Utils.getFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //业务队列消息消费
        channel.basicConsume(Config.BUSINESS_QUEUE,false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, StandardCharsets.UTF_8);
                long deliveryTag = envelope.getDeliveryTag();
                if (Objects.equals("ok",message)){
                    channel.basicAck(deliveryTag,false);
                    log.info("消息正常签收");
                }else {
                    //requeue参数需要设置成false,表示不再进入原队列。如果为false则不会进入死信队列
                    channel.basicNack(deliveryTag,false,false);
                    log.info("消息未签收,进入到死信队列,消息内容:{}",message);
                }
            }
        });
        //死信队列消息消费
        channel.basicConsume(Config.DEAD_QUEUE,true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, StandardCharsets.UTF_8);
                log.info("死信队列收到消息内容:{}",message);
            }
        });
    }
}
